import { Controller } from 'egg';
import { Result } from '../util/result';
import MsgEnum from '../util/msgEnum';
import { Op } from 'sequelize';
import xlsx from 'node-xlsx';
import { get, isExistObject } from '../util/ossFile';
import RoleEnum from '../util/roleEnum';

const toArray = require('stream-to-array');

export default class TalentController extends Controller {
  public async getTalentMaps() {
    const { ctx } = this;
    const data = await this.ctx.service.talent.getTalentMaps();
    if (data) {
      ctx.body = new Result(data, MsgEnum.GET_FINANCIAL_LIST_SUCCESS);

    } else {
      ctx.status = 400;
      ctx.body = new Result(data, MsgEnum.GET_FINANCIAL_LIST_SUCCESS);

    }
  }

  async talentList() {
    const { ctx, app } = this;
    const errors = app.validator.validate(
      {
        page: { type: 'int', require: true, allowEmpty: false },
        name: { type: 'string', require: true, allowEmpty: true },
        talentType: { type: 'string', require: true, allowEmpty: true },
        organization: { type: 'string', require: true, allowEmpty: true },
        date: { type: 'string', require: true, allowEmpty: true },
      },
      ctx.request.body
    );
    if (errors) {
      ctx.status = 400;
      ctx.body = new Result(errors, MsgEnum.PARAMETER_VERIFICATION_ERROR);
    } else {
      const { page, name, talentType, organization, date } = ctx.request.body;
      const res = await ctx.service.talent.talentList(
        page,
        name,
        talentType,
        organization,
        date
      );
      ctx.body = new Result(res);
    }
  }

  async insertTalent() {
    const { ctx } = this;

    await ctx.getFileStream()
      .then(async r => {
        const result = await this.ctx.service.talent.insertTalent(r.fields, r);
        if (result.mainData) {
          ctx.body = result;
        } else {
          ctx.status = 406;
          ctx.body = result;
        }
      });
  }

  async delTalent() {
    const { ctx, app } = this;
    const errors = app.validator.validate(
      {
        uuid: { type: 'array', required: true, allowEmpty: false },
      },
      ctx.request.body
    );
    if (errors) {
      ctx.status = 400;
      ctx.body = new Result(errors, MsgEnum.PARAMETER_VERIFICATION_ERROR);
    } else {
      const { uuid } = ctx.request.body;
      const res = await ctx.service.talent.delTalent(uuid);
      ctx.body = new Result(res);
    }
  }

  async uploadFiles() {

    const { ctx } = this;
    const stream = await ctx.getFileStream();
    const newBuffer = await toArray(stream)
      .then(function (parts) {
        const buffers = [];
        for (let i = 0, l = parts.length; i < l; ++i) {
          const part = parts[i];
          buffers.push((part instanceof Buffer) ? part as never : new Buffer(part) as never);
        }
        return Buffer.concat(buffers);
      });
    const parse = xlsx.parse(newBuffer, { bookType: 'xlsx', bookSST: false, type: 'buffer' });
    const data = parse[0].data.slice(3);
    const res = await this.ctx.service.talent.insertTalents(
      data,
      stream.fields.filler
    );

    if (res.mainData) {
      ctx.body = res;
    } else {
      ctx.status = 406;
      ctx.body = res;
    }
  }

  async update() {
    const { ctx } = this;

    await ctx.getFileStream()
      .then(async r => {

        const result = await this.ctx.service.talent.update(r.fields, r);
        if (result.mainData) {
          ctx.body = result;
        } else {
          ctx.status = 406;
          ctx.body = result;
        }
      });
  }

  public async getTalentAttachment() {
    const { ctx } = this;

    const { id } = ctx.query;
    const result = await get(RoleEnum.TALENT, Number(id), '.pdf');
    if (result.error) {
      ctx.status = 406;
      ctx.body = result;
    } else {
      this.ctx.attachment(result.file_name);
      this.ctx.set('Content-Type', 'application/octet-stream');
      ctx.body = result.result.stream;
    }
  }

  public async hasFile() {
    const { ctx } = this;
    const { id } = ctx.request.body;
    const res = await isExistObject(RoleEnum.TALENT, Number(id), '.pdf');
    if (res?.exist) {
      ctx.body = new Result(res, res.msg);
    } else {
      ctx.status = 404;
      ctx.body = new Result(res, res.msg);
    }
  }

  public async hasSameTel() {
    const { ctx } = this;
    const { tel, uuid } = ctx.request.body;
    if (tel && uuid) {
      const t = await ctx.model.Talent.findAll({
        where: { tel, uuid: { [Op.ne]: uuid } },
      });
      const res = t.length !== 0;

      ctx.body = new Result(res);
    } else {
      const t = await ctx.model.Talent.findAll({ where: { tel } });
      const res = t.length !== 0;
      ctx.body = new Result(res);
    }
  }
}
